﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="AttachedObject.cs" company="JDML Consulting Ltd.">
//   Copyright 2011 Photon Project - http://photon.codeplex.com
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace Photon.Windows
{
    using System;
    using System.Windows;
    using System.Windows.Interactivity;

    public abstract class AttachedObject<T> : 
#if SILVERLIGHT
        DependencyObject
#else
        Freezable
#endif
    , IAttachedObject where T : DependencyObject
    {
        public T AssociatedObject { get; private set; }

        #region IAttachedObject Members

        void IAttachedObject.Attach(DependencyObject associatedObject)
        {
            var value = Guard.ArgumentWrongType<T>("associatedObject", associatedObject);
            if (AssociatedObject != value)
            {
                if (AssociatedObject != null)
                {
                    throw new InvalidOperationException();
                }

                AssociatedObject = value;
                OnAttached(associatedObject);
            }
        }

        void IAttachedObject.Detach()
        {
            if (AssociatedObject != null)
            {
                var associatedObject = AssociatedObject;
                AssociatedObject = null;
                OnDetached(associatedObject);
            }
        }

        DependencyObject IAttachedObject.AssociatedObject
        {
            get { return AssociatedObject; }
        }

        #endregion

        protected virtual void OnAttached(object associatedObject)
        {
        }

        protected virtual void OnDetached(object associatedObject)
        {
        }
    }
}